package com.hxc.dao;

import com.hxc.user.UserData;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDataDao {
  private static final String SQL_INS = "INSERT INTO userdata(user_id,nick_name,sex,age) VALUES (?,?,?,?)";

  private static final String SQL_UPD = "UPDATE userdata SET nick_name=?,sex=?,age=? WHERE userid=?";

  private static final String SQL_SEL = "SELECT user_id,nick_name,sex,age FROM userdata ";

  private static final String SQL_DEL = "DELETE FROM userdata WHERE user_id = ?";

  private final Connection conn;

  public UserDataDao(Connection conn) {
    this.conn = conn;
  }

  public int insert(UserData data) {
    try (PreparedStatement ps = this.conn.prepareStatement(SQL_INS)) {
      ps.setString(1, data.getUserId());
      ps.setString(2, data.getNickName());
      ps.setString(3, data.getSex());
      ps.setInt(4, data.getAge());

      return ps.executeUpdate();
    } catch (SQLException e) {
      throw new IllegalStateException("数据库查询错误, " + e.getMessage(), e);
    }
  }

  public int update(UserData data) {
    try (PreparedStatement ps = this.conn.prepareStatement(SQL_UPD)) {
      ps.setString(1, data.getNickName());
      ps.setString(2, data.getSex());
      ps.setInt(3, data.getAge());
      ps.setString(4, data.getUserId());

      return ps.executeUpdate();
    } catch (SQLException e) {
      throw new IllegalStateException("数据库查询错误, " + e.getMessage(), e);
    }
  }

  public int delete(String userId) {
    try (PreparedStatement ps = this.conn.prepareStatement(SQL_DEL)) {
      ps.setString(1, userId);

      return ps.executeUpdate();
    } catch (SQLException e) {
      throw new IllegalStateException("数据库查询错误, " + e.getMessage(), e);
    }
  }

  public List<UserData> selectAll() {
    ArrayList<UserData> result = new ArrayList<UserData>();
    try (PreparedStatement ps = this.conn.prepareStatement(SQL_SEL)) {

      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
        result.add(convert(rs));
      }
      return result;
    } catch (SQLException e) {
      throw new IllegalStateException("数据库查询错误, " + e.getMessage(), e);
    }
  }

  public UserData selectByUserId(String userId) throws SQLException {
    UserData result = null;
    try (PreparedStatement ps = conn.prepareStatement(SQL_SEL + "WHERE user_id = ?")) {
      ps.setString(1, userId);
      ResultSet rs = ps.executeQuery();
      if (rs.next()) {
        result = convert(rs);
      }
      return result;
    } catch (SQLException e) {
      throw new SQLException(e.getMessage());
    }
  }

  private UserData convert(ResultSet rs) throws SQLException {
    UserData data = new UserData();
    int index = 1;
    data.setUserId(rs.getString(index++));
    data.setNickName(rs.getString(index++));
    data.setSex(rs.getString(index++));
    data.setAge(rs.getInt(index++));

    return data;
  }
}
